//
//  LYContactViewController.swift
//  WeChat
//
//  Created by mac on 2018/7/24.
//  Copyright © 2018年 RRC. All rights reserved.
//

import UIKit
import SwiftyJSON

class LYContactViewController: UIViewController {

    var listTableView:UITableView!
    
    let cellIdent = "CellIdentifier"
    
    //UITableView 右侧索引栏的 value
    fileprivate var sortedkeys = [String]()
    fileprivate var dataDict:Dictionary<String, NSMutableArray>?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        self.title = "通讯录"
        self.view.backgroundColor = UIColor.viewBackgroundColor
        
        listTableView = UITableView()
        listTableView.backgroundColor = UIColor.init(ts_hexString: "#EFEFF4")
        listTableView.delegate = self
        listTableView.dataSource = self
        listTableView.estimatedRowHeight = 54
        listTableView.sectionIndexColor = UIColor.darkGray
        self.view.addSubview(listTableView)
        listTableView.snp.makeConstraints { (make) in
            make.edges.equalTo(0)
        }
        listTableView.register(LYContactTableViewCell.self, forCellReuseIdentifier: cellIdent)
        
        self.fetchContactList()
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func fetchContactList(){
        guard let JSONData = Data.ts_dataFromJSONFile("contact") else {
            return
        }
        
        let jsonObject = try! JSON(data: JSONData)
        //创建群聊和公众账号的数据
        let topArray: NSMutableArray = [
            ContactModelEnum.newFriends.model,
            ContactModelEnum.groupChat.model,
            ContactModelEnum.tags.model,
            ContactModelEnum.publicAccout.model
        ]
        
        //添加 群聊和公众账号的数据的key
        sortedkeys.append("")
        dataDict = ["" : topArray]
        
        //解析星标联系人数据
        if let startArray = jsonObject["data"][0].array, startArray.count > 0 {
            let tempList = NSMutableArray()
            for dict in startArray {
                let model = ContactModel()
                model.mapping(map: dict)
                tempList.add(model)
            }
            tempList.sortedArray(using: #selector(ContactModel.compareContact(_:)))
            sortedkeys.append("★")
            dataDict!["★"] = tempList
            
        }
        
        //解析联系人数据
        if let contactArray = jsonObject["data"][1].array, contactArray.count>0{
            let temList = NSMutableArray()
            for dict in contactArray {
                let model = ContactModel()
                model.mapping(map: dict)
                temList.add(model)
            }
            
            // 重新 a-z 排序
            var dataSource = Dictionary<String, NSMutableArray>()
            for index in 0..<temList.count{
                let contactModel:ContactModel = temList[index] as! ContactModel
                guard let nameSpell:String = contactModel.nameSpell else {
                    continue
                }
                let lowerBound = String.Index(encodedOffset: 0)
                let upperBound = String.Index(encodedOffset:1)
                let firstLettery:String = nameSpell[lowerBound..<upperBound].uppercased()
                if let letterArray:NSMutableArray = dataSource[firstLettery]{
                    letterArray.add(contactModel)
                }else{
                    let tempArray = NSMutableArray()
                    tempArray.add(contactModel)
                    dataSource[firstLettery] = tempArray
                }
            }
            
            let sortedKeys = Array(dataSource.keys).sorted(by: <)
            sortedkeys.append(contentsOf: sortedKeys)
            dataDict = dataDict! + dataSource
            
        }
        
    }
    
    
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

// MARK: UITableViewDelegate
extension LYContactViewController: UITableViewDelegate{
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return listTableView.estimatedRowHeight
    }
    
}

// MARK: UITableViewDataSource
extension LYContactViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return sortedkeys.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let key:String = sortedkeys[section]
        let dataArray:NSMutableArray = dataDict![key]!
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:LYContactTableViewCell = tableView.dequeueReusableCell(withIdentifier: cellIdent) as! LYContactTableViewCell
        
        //判断数组越界问题
        guard indexPath.section < sortedkeys.count else {
            return cell
        }
        
        let key:String = sortedkeys[indexPath.section]
        let dataArray:NSMutableArray = dataDict![key]!
        cell.setCellContent(dataArray[indexPath.row] as! ContactModel)
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 0 {
            return nil
        }
        let title = sortedkeys[section]
        if title == "★" {
            return "★ 星标朋友"
        }
        return title
    }
    
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        guard let _ = dataDict else{
            return []
        }
        let titles:[String] = sortedkeys
        return titles
    }
    
}
